package com.example.donghuatest;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Scroller;
import android.widget.TextView;

public class MainActivity extends Activity{
	private Handler mHandler = new Handler();
	private View ivVoiceCancel;
	private ViewGroup text_entry;
	private ViewGroup voice_note_layout;
	private TextView tv_voice_note;
	private TextView mRecordTime;
	ImageView bt_voice;
	ImageView iv_voice;
	ImageView gai;
	private String mTimerFormat;
	Animation cancle_animation;
	int pop_flag = 0;
	Animation mic_fling;
	Animation trash_lid_start;
	Animation slide_in_right;
	Animation slide_in_left;
	Animation slide_out_left;
	Animation slide_out_right;
	private long startVoiceT, endVoiceT;
	private ViewGroup trashcan;
	private Animation push_up_in;
	private Animation push_up_out;
	private ImageButton emoji_btn;
	private Animation grow_from_top;
	private Animation mic_twinkle;
	private FrameLayout scroller_view;
	/**
	 * 滑动类
	 */
	private Scroller scroller;
	/**
	 * 屏幕宽度
	 */
	private int screenWidth;
	
	/**
	 * 手指按下X的坐标
	 */
	private int downY;
	/**
	 * 手指按下Y的坐标
	 */
	private int downX;
	private ScrollUtils utils ;
	int raw_x ;
	private boolean flagmv=false;
	private AudioUtils audioUtils;
	private int flag = 1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN|WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);// 默认不弹出软键盘
		this.setVolumeControlStream(AudioManager.STREAM_MUSIC); //注册的默认 音频通道
		DisplayMetrics dm = new DisplayMetrics();
		((WindowManager) this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(dm);
		 screenWidth = dm.widthPixels;
		 scroller = new Scroller(this);
		utils = new ScrollUtils();
		audioUtils = new AudioUtils(this);
		initWidget();
		initAnimation();
		bt_voice.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				flagmv=true;
				// 按下语音录制按钮时返回false执行父类OnTouch
				return MainActivity.this.onTouchEvent(event);
			}
		});
		bt_voice.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				audioUtils.playSound(1);
				audioUtils.playSound(2);
				if (pop_flag == 0) {// 防止popup被多次点击重复出现
					showpopup();
				}
				
			}
		});
		 scroller_view.setOnTouchListener(new View.OnTouchListener() {
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// 按下语音录制按钮时返回false执行父类OnTouch
					return MainActivity.this.onTouchEvent(event);
				}

			}); 
	}

	// 初始化动画
	private void initAnimation() {
		cancle_animation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.voice_cancle);
		slide_in_right = AnimationUtils.loadAnimation(MainActivity.this, R.anim.slide_in_right);
		slide_in_left = AnimationUtils.loadAnimation(MainActivity.this, R.anim.slide_in_left);
		slide_out_left = AnimationUtils.loadAnimation(MainActivity.this, R.anim.slide_out_left);
		slide_out_right = AnimationUtils.loadAnimation(MainActivity.this, R.anim.slide_out_right);
		mic_fling = AnimationUtils.loadAnimation(MainActivity.this, R.anim.actin);
		trash_lid_start = AnimationUtils.loadAnimation(MainActivity.this, R.anim.lid_start);
		push_up_in = AnimationUtils.loadAnimation(MainActivity.this, R.anim.push_up_in);
		push_up_out = AnimationUtils.loadAnimation(MainActivity.this, R.anim.push_up_out);
		grow_from_top = AnimationUtils.loadAnimation(MainActivity.this, R.anim.grow_from_top);
		mic_twinkle = AnimationUtils.loadAnimation(MainActivity.this, R.anim.mic_twinkle);
	}
	// 初始化控件
	private void initWidget() {
		scroller_view = (FrameLayout) findViewById(R.id.voice_note_slide_to_cancel_scroller);  
		bt_voice = (ImageView) findViewById(R.id.voice_note_btn);
		voice_note_layout = (ViewGroup) findViewById(R.id.voice_note_layout);
		ivVoiceCancel = (View) findViewById(R.id.voice_note_slide_to_cancel_animation);
		text_entry = (ViewGroup) findViewById(R.id.text_entry_layout);
		tv_voice_note = (TextView) findViewById(R.id.voice_note_slide_to_cancel);
		mRecordTime = (TextView) findViewById(R.id.voice_note_info);
		trashcan = (ViewGroup) findViewById(R.id.voice_cancel_trashcan);
		emoji_btn = (ImageButton) findViewById(R.id.emoji_picker_btn);
		mTimerFormat = getResources().getString(R.string.timer_format);
		iv_voice = (ImageView) findViewById(R.id.voice_cancel_animation);
		gai = (ImageView) findViewById(R.id.voice_cancel_trashcan_lid);
	}
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (flagmv) {
			utils.addVelocityTracker(event);
			utils.getScrollVelocity();
			int x= (int) event.getX();
			raw_x = (int) event.getRawX();
			int[] loc_bt_voice = new int[2];
			bt_voice.getLocationOnScreen(loc_bt_voice);
			int bt_voice_x = loc_bt_voice[0];
			if (event.getAction() == MotionEvent.ACTION_DOWN && flag == 1) {
					//在播放录音就停止该播放
					utils.addVelocityTracker(event);
					utils.scrollByDistanceX(scroller_view);
					audioUtils.playSound(1);
					_layoutNormal2CancelAnimation();
					// 假如scroller滚动还没有结束，我们直接返回
					if (!scroller.isFinished()) {
						return super.onTouchEvent(event);
					}
					downX = (int) event.getRawX();
					downY = (int) event.getY();
					startVoiceT = System.currentTimeMillis();
					flag = 2;
					updateTimerView();
					flagmv = false;
					//设置名称开始录音
			} else if (event.getAction() == MotionEvent.ACTION_UP && flag == 2) {
				_layoutCancel2NormalAnimation();
				int time = (int) ((endVoiceT - startVoiceT) / 1000);
				if (time < 60) {
					//获取路径
					if (time <= 1) {
						flag = 1;
						flagmv = false;
						return false;
					}
					//不发送语音
				}
				// 松开手势时执行录制完成
				
				flagmv = false;
				flag = 1;
			}else if(event.getAction() == MotionEvent.ACTION_MOVE){
				int deltaX = downX -raw_x;
				if(event.getX() + bt_voice_x> bt_voice_x
						&& event.getX() + bt_voice_x< bt_voice_x + bt_voice.getWidth()){
					//手指在录音按钮范围内滑动时，文字不触发滑动事件
				}else{//否则触发滑动事件
					scroller_view.scrollBy(deltaX, 0);// 手指拖动itemView滚动, deltaX大于0向左滚动，小于0向右滚
				}
				downX =raw_x;//记住上次触摸屏的位置
				if ((raw_x < screenWidth/2 + 50)&&flag==2) {// 手指滑到屏幕一半时执行取消事件
					utils.scrollByDistanceX(scroller_view);
					utils.recycleVelocityTracker();
					_layoutCancel2NormalAnimation();
					audioUtils.playSound(2);
					_trashcanAndMicAnimation();
					flag = 1;
					return false;
				} else {
					
				}
			}
			flagmv = false;
		}
		return super.onTouchEvent(event);
	}
	/**
	 * 正常布局切换到取消布局
	 */
	private void _layoutNormal2CancelAnimation() {
		voice_note_layout.startAnimation(slide_in_right);//录音布局右滑进入
		voice_note_layout.setVisibility(View.VISIBLE);
		text_entry.startAnimation(slide_out_left);// 文本布局左滑出去
		text_entry.setVisibility(View.GONE);
		ivVoiceCancel.startAnimation(cancle_animation);// 波纹动画
		iv_voice.setVisibility(View.VISIBLE);
		iv_voice.startAnimation(mic_twinkle);//mic闪烁动画
	}
	
	/**
	 * 垃圾桶和话筒动画
	 */
	private void _trashcanAndMicAnimation(){
		iv_voice.startAnimation(mic_fling); // mic抛掷动画
		emoji_btn.setVisibility(View.INVISIBLE);
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				gai.startAnimation(trash_lid_start);// 桶盖动画
			}
		}, 600);
		trashcan.startAnimation(push_up_in);//垃圾桶上滑进入
		trashcan.setVisibility(View.VISIBLE);
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				trashcan.startAnimation(push_up_out);//垃圾桶下滑出去
				trashcan.setVisibility(View.INVISIBLE);
			}
		}, 1500);
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				emoji_btn.startAnimation(grow_from_top);
				emoji_btn.setVisibility(View.VISIBLE);
			}
		}, 1600);
	}
	
	/**
	 * 取消布局切换到正常布局
	 */
	private void _layoutCancel2NormalAnimation() {
		voice_note_layout.setVisibility(View.GONE);
		voice_note_layout.startAnimation(slide_out_right);//录音布局右滑出去
		text_entry.setVisibility(View.VISIBLE);
		text_entry.startAnimation(slide_in_left);// 文本布局左滑进入
		ivVoiceCancel.clearAnimation();//取消波纹动画
		iv_voice.clearAnimation();
		iv_voice.setVisibility(View.GONE);
	}

	/**
	 * 弹出popup提示
	 */
	private void showpopup() {
		pop_flag = 1;
		LinearLayout layout = new LinearLayout(this);
		TextView tv = new TextView(this);
		tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
		tv.setText("按住录音，松开发送");
		tv.setTextColor(Color.WHITE);
		layout.addView(tv);
		final PopupWindow popupWindow = new PopupWindow(layout,LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		popupWindow.setFocusable(false);
		popupWindow.setOutsideTouchable(false);// 使popup点击窗口外侧不消失
		popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.popup_inline_error_above_holo_light));
		popupWindow.setTouchable(false);
		int[] location = new int[2];
		bt_voice.getLocationOnScreen(location);
		popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
		popupWindow.showAtLocation(bt_voice, Gravity.TOP, location[0],location[1] - bt_voice.getWidth());
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				popupWindow.dismiss();
				pop_flag = 0;
			}
		}, 2000);
	}
	private void updateTimerView() {// 时间更新
		endVoiceT = System.currentTimeMillis();
		int time = (int) ((endVoiceT - startVoiceT) / 1000);
		String timeStr = String.format(mTimerFormat, time / 60, time % 60);
		mRecordTime.setText(timeStr);
		if (time < 60) {
			mHandler.postDelayed(mUpdateTimer, 500);
		} else {

		}
	}
	private Runnable mUpdateTimer = new Runnable() {
		@Override
		public void run() {
			updateTimerView();
		}
	};
}
